/**
 * Created by sky on 8/30/2017.
 */
require('../models/food.model');
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
let foodModel = mongoose.model('foods');

module.exports = {
    findAllFoods: findAllFoods,
    addFood:addFood,
    updateFood:updateFood,
    deleteFood:deleteFood,
    findFoodByCategories:findFoodByCategories
};

function findAllFoods(merchant,callback) {
    foodModel.find({merchant:merchant}, function(err, foods){
        if(err) {
            console.error(err);
        }
        console.log(err, foods);
        callback(null, foods);
    })
};

// function findAllFoods(callback) {
//     foodModel.find({},function(err, foods){
//         if(err) {
//             console.error(err);
//         }
//         console.log(err, foods);
//         callback(null, foods);
//     })
// };

function addFood(food,callback) {
    console.log("add food facade");
    let foodDB = new foodModel(food);
    foodDB.save(function(err,result){
         if(err) {
            console.error(err);
        }
        console.log(err, result);
        callback(null, result);
    })
};

function updateFood(food,callback){
     console.log("update food facade");
    foodModel.update(
        {_id:food._id},
        {$set:{"name":food.name,"price":food.price,"image":food.image,"categories":food.categories}},
        function(err,result){
         if(err) {
            console.error(err);
        }
        console.log(err, result);
        callback(null, result);
    })
};

function deleteFood(id,callback){
     console.log("delete food facade");
    foodModel.remove(
        {_id:id},
        function(err,result){
         if(err) {
            console.error(err);
        }
        console.log(err, result);
        callback(null, result);
    })
};

function findFoodByCategories(merchantId,categories,callback){
     console.log("find caegories food facade");
    foodModel.find({categories:categories,merchant:merchantId},function(err, result){
            if(err) {
                console.error(err);
            }
            console.log(err, result);
            callback(null, result);
        });
    };

//测试用
// function findFoodByCategories(categories,callback){
//      console.log("find caegories food facade");
//     foodModel.find({categories:categories},function(err, result){
//             if(err) {
//                 console.error(err);
//             }
//             console.log(err, result);
//             callback(null, result);
//         });
//     };
